package com.bdtop.dbl.ui.activities.fragments;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bdtop.dbl.BaseFragment;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.bluetooth.BluetoothLeService;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.GetImgResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.thirdparty.map.OfflineMapDownActivity;
import com.bdtop.dbl.ui.ShareActivity;
import com.bdtop.dbl.ui.activities.acccount.LogActivity;
import com.bdtop.dbl.ui.activities.acccount.LoginActivity;
import com.bdtop.dbl.ui.activities.acccount.UpdatePasswordActivity;
import com.bdtop.dbl.ui.activities.device.FenceListActivity;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.activities.me.AboutActivity;
import com.bdtop.dbl.ui.activities.me.MsgActivity;
import com.bdtop.dbl.ui.view.SelectDialog;
import com.bdtop.dbl.ui.view.SelectDialog.DialogInterfaceListener;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.ImageUtils;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

import java.io.File;

/**
 * @ClassName: MineFragment
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-26
 */
@SuppressLint("SdCardPath")
public class MineFragment extends BaseFragment implements OnClickListener {

	private View layoutAbout, layoutMsg, layoutOperlog, layoutSafe, layoutUpdateTouxiang,
	// layoutImg,
			layoutFences, layoutLoginOut, layoutOfflineMap;
	private ImageView imgTouxiang;
	// private TextView name;
	private ProgressBar progressBar;

	private View imgNewMessage;

	@Override public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			((MainActivity) holder).hiddenWaitingMessage();
		}
	}

	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_mine, container, false);
		initViews(view);

		return view;
	}

	private void initViews(View view) {
		imgNewMessage = view.findViewById(R.id.img_new_message);
		layoutAbout = view.findViewById(R.id.layout_about);
		layoutMsg = view.findViewById(R.id.layout_msg);
		layoutOperlog = view.findViewById(R.id.layout_operlog);
		layoutSafe = view.findViewById(R.id.layout_safe);
		layoutUpdateTouxiang = view.findViewById(R.id.layout_update_touxiang);
		// name = (TextView) view.findViewById(R.id.tv_name);
		layoutFences = view.findViewById(R.id.layout_fences);
		layoutLoginOut = view.findViewById(R.id.layout_login_out);
		layoutOfflineMap = view.findViewById(R.id.layout_offline_map);
		progressBar = (ProgressBar) view.findViewById(R.id.progress);
		layoutAbout.setOnClickListener(this);
		layoutMsg.setOnClickListener(this);
		layoutOperlog.setOnClickListener(this);
		layoutSafe.setOnClickListener(this);
		layoutUpdateTouxiang.setOnClickListener(this);
		layoutFences.setOnClickListener(this);
		layoutLoginOut.setOnClickListener(this);
		layoutOfflineMap.setOnClickListener(this);
		view.findViewById(R.id.layout_share).setOnClickListener(this);
		imgTouxiang = (ImageView) view.findViewById(R.id.img_touxiang);

		String imgid = Preferences.getUserName(getActivity());
		// 从手机提取用户头像
		String localBase64 = Preferences.getUserImgBase64(getActivity(), imgid);
		// 准备默认头像
		Bitmap defaultImg = ImageUtils.toRoundBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.default_user_head));
		Bitmap localBitmap = null;
		if ("".equals(localBase64)) {
			// 如果本地头像不存在，设置为默认头像
			imgTouxiang.setImageBitmap(defaultImg);
			// 同时去服务器请求用户头像
			requestHead();
		} else {
			// 本地头像有异常，清空本地文件
			try {
				localBitmap = ImageUtils.base64ToBitmap(localBase64.replaceAll(getResources().getString(R.string.add_mark), "+"));
			} catch (Exception e) {
				Preferences.saveUserImg(getActivity(), "", imgid);
				localBitmap = defaultImg;
			}
			imgTouxiang.setImageBitmap(ImageUtils.toRoundBitmap(localBitmap));
		}

		TextView txAddress = (TextView) view.findViewById(R.id.tv_address);
		String address = Preferences.getLocationInfo(holder);
		String city = holder.getString(R.string.city);
		txAddress.setText(address.replaceFirst(city, city + "\n"));
	}

	/**
	 * 服务器请求用户头像
	 */
	private void requestHead() {
		final String imgid = Preferences.getUserName(getActivity());
		ServerApiFactory.getApiImpl().getImg(loginSign, imgid, new RequestCallback() {
			@Override public void onSuccess(String rawData, Object response) {
				GetImgResponse getImgResponse = (GetImgResponse) response;

				if (getImgResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					if (null != getImgResponse.getImgdata() && !"".equals(getImgResponse.getImgdata())) {
						String base64 = getImgResponse.getImgdata();
						// 存入本地
						Preferences.saveUserImg(holder, base64, imgid);
						Bitmap bm = null;
						try {
							bm = ImageUtils.base64ToBitmap(base64.replaceAll(getResources().getString(R.string.add_mark), "+"));
						} catch (Exception e) {
						}
						if (null != bm) {
							imgTouxiang.setImageBitmap(ImageUtils.toRoundBitmap(bm));
						}
					}
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				// imgTouxiang.setImageBitmap(defaultImg);
			}
		});
	}

	@Override public void onClick(View view) {
		if (isHidden) // fix bug
			return;

		switch (view.getId()) {
		case R.id.layout_about:
			AboutActivity.launch(getActivity());
			break;
		case R.id.layout_msg:
			MsgActivity.launch(getActivity());
			break;
		case R.id.layout_operlog:
			LogActivity.launch(getActivity());
			break;
		case R.id.layout_safe:
			UpdatePasswordActivity.launch(getActivity());
			break;
		case R.id.layout_update_touxiang:
			showModiHeadDialog();
			break;
		case R.id.layout_fences:
			// String mdn = DBLApplication.getInstance().currentDeviceMdn;
			String mdn = DBLApplication.getInstance().currentDi.mdn;
			if (TextUtils.isEmpty(mdn)) {
				showToast(R.string.no_device_bind);
			} else {
				FenceListActivity.launch(getActivity(), mdn);
			}
			break;
		case R.id.layout_login_out:
			showDeleteDialog();
			break;
		case R.id.layout_offline_map:
			OfflineMapDownActivity.launch(holder);
			break;
		case R.id.layout_share:
			ShareActivity.launch(holder);
			break;
		}
	}

	private void showDeleteDialog() {
		final Dialog dialog = new Dialog(holder, R.style.Theme_Light_NoTitle_Dialog);
		View content = LayoutInflater.from(holder).inflate(R.layout.dialog_confirm_2, null);

		TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
		txMessage.setText(R.string.exitTip);

		OnClickListener listener = new OnClickListener() {
			@Override public void onClick(View arg0) {
				dialog.dismiss();

				if (arg0.getId() == R.id.btn_confirm) {
					loginOut();
				}
			}
		};

		content.findViewById(R.id.btn_confirm).setOnClickListener(listener);
		content.findViewById(R.id.btn_cancel).setOnClickListener(listener);

		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(content);
		dialog.show();
	}

	private void loginOut() {
		holder.showWaitingDialog(R.string.login_outing, false, true);
		ServerApiFactory.getApiImpl().loginOut(Preferences.getLoginSign(getActivity()), new RequestCallback() {

			@Override
			public void onSuccess(String rawData, Object response) {
				BaseResponse baseResponse = (BaseResponse) response;
				if (baseResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {

//					stopBleService();
					
					if(holder != null){
						((MainActivity)holder).releaseGatt();
					}
					
					DBLDebug.logd("logout clear parmas start...");
					clearLoginParams();
					DBLDebug.logd("logout clear parmas end...");

					LoginActivity.launch(getActivity());
					getActivity().finish();
				} else {
					showToast(R.string.login_out_error);
				}
				holder.dismissDialog();
			}

			@Override
			public void onError(int statusCode, Throwable e, String rawData) {
				if (NetworkUtils.isNetConnect(holder)) {
					holder.showToast(R.string.oper_error);
				} else {
					holder.showToast(R.string.net_error);
				}
				holder.dismissDialog();
			}
		});
	}

	public void clearLoginParams() {
		String username = Preferences.getUserName(getActivity());
		// fix: 注销 保留 账号密码
		// Preferences.saveUserName(getActivity(), "");
		// Preferences.savePassword(getActivity(), "");
		// Preferences.setRememberPwd(getActivity(), false);

		// fix: 一次性commit
		// Preferences.setAutoLogin(getActivity(), false);
		// Preferences.saveLoginStatus(getActivity(), false);
		// Preferences.saveLastLoginUser(getActivity(),username);

		// Editor editor = Preferences.getPreferences(getActivity()).edit();
		// editor.putBoolean(Preferences.AUTO_LOGIN, false);
		// editor.putBoolean(Preferences.ISLOGIN, false);
		// editor.putString(Preferences.LAST_LOGIN_USER, username);
		// editor.commit();

		// fix : db
		Preferences.clearLoginParams(username);

		DBLApplication.getInstance().deviceInfoList = null;
		DBLApplication.getInstance().currentDi = null;
	}

	int REQUEST_CODE_IMAGE_FORM_ALBUM = 1;
	int REQUEST_CODE_IMAGE_FROM_CAMERA = 2;
	int REQUEST_CODE_IMAGE_FROM_CROP = 3;

	String tempPhotoName = "userHead.jpg";

	protected void getImageFromCamera() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FORM_ALBUM);
	}

	protected void getImageFromAlbum() {
		// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/" + tempPhotoName)));
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CAMERA);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CROP);
	}

	private String photoPath;
	private Bitmap photo;

	@SuppressWarnings("static-access") @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == holder.RESULT_OK) {

			if (requestCode == REQUEST_CODE_IMAGE_FORM_ALBUM) {
				startPhotoZoom(data.getData());
			} else if (requestCode == REQUEST_CODE_IMAGE_FROM_CAMERA) {
				photoPath = "/sdcard/" + tempPhotoName;
				File temp = new File(photoPath);
				startPhotoZoom(Uri.fromFile(temp));
			} else if (requestCode == REQUEST_CODE_IMAGE_FROM_CROP) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					photo = extras.getParcelable("data");
				} else {
					Toast.makeText(holder, R.string.tailoring_error, Toast.LENGTH_SHORT).show();
				}
			}
		}

		if (null != photo) {
			photo = ImageUtils.compressImage(photo);
			String sign = Preferences.getLoginSign(getActivity());
			String imgid = Preferences.getUserName(getActivity());
			// final String imgName =
			// String.valueOf(System.currentTimeMillis());
			final String imgData = ImageUtils.bitmapToBase64(null, photo).replace("+", getResources().getString(R.string.add_mark));

			ServerApiFactory.getApiImpl().updateImgRequest(sign, imgid, imgData, new RequestCallback() {

				@Override public void onSuccess(String rawData, Object response) {
					BaseResponse baseResponse = (BaseResponse) response;
					if (baseResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
						imgTouxiang.setImageBitmap(ImageUtils.toRoundBitmap(photo));
					}
					holder.showToast(baseResponse.getDesc());
					progressBar.setVisibility(View.GONE);
					imgTouxiang.setVisibility(View.VISIBLE);
					photo = null;

					Preferences.saveUserImg(getActivity(), imgData, Preferences.getUserName(getActivity()));
					// Preferences.saveUserImgName(getActivity(),
					// imgName,
					// Preferences.getUserName(getActivity()));
				}

				@Override public void onError(int statusCode, Throwable e, String rawData) {
					if (NetworkUtils.isNetConnect(holder)) {
						showToast(R.string.oper_error);
					} else {
						showToast(R.string.net_error);
					}
					progressBar.setVisibility(View.GONE);
					imgTouxiang.setVisibility(View.VISIBLE);
					photo = null;
				}
			});
			progressBar.setVisibility(View.VISIBLE);
			imgTouxiang.setVisibility(View.GONE);
		}
	}

	private void showModiHeadDialog() {
		SelectDialog dialog = new SelectDialog(getActivity(), new DialogInterfaceListener() {

			@Override public void photoListener(Dialog mDialog) {
				getImageFromAlbum();
			}

			@Override public void cameraListener(Dialog mDialog) {
				getImageFromCamera();
			}
		});
		dialog.show();
	}

}
